
"""
获取数据表
"""
import json

from core.state import AnalyzeState
from langgraph.types import Command
from langgraph.config import get_stream_writer
from core.utils.mcp_function import call_tool
from core.llm import userinfo_analyzer
from config import settings
from loguru import logger
from models.userinfo import UserInfoData


async def userinfo_node(state: AnalyzeState):

    writer = get_stream_writer()
    writer("获取用户信息")
    logger.info("获取用户信息")

    user_data = await call_tool(
        sse_url=settings.DATA_SERVER_URI,
        tool_name = 'system#userInfoBySessionId',
        tool_args = {
            'sessionId': state.get('sessionId')
        }
    )
    logger.info(f'用户详细信息：{user_data}')

    if not isinstance(user_data, dict):
        return Command(update={"userinfo": UserInfoData()}, goto='schemas')

    query = state.get('query')
    profile = userinfo_analyzer.invoke(user_data=user_data, query=query)

    userinfo = UserInfoData(
        description=json.dumps(profile, ensure_ascii=False),
        data=user_data
    )
    writer(userinfo)
    logger.info(f'用户简略信息：{profile}')

    return Command(update={"userinfo": userinfo}, goto='schemas')
